import { Op, Sequelize } from 'sequelize'
import dayjs from 'dayjs'
import { MsgModel } from '../../until/context'
import { IfindParmas } from '../../until/Interface'

class ErrorService { 
        public static async myFindAll(options: IfindParmas) {
        let {startPosition,limit,where,attributes,model}:{startPosition: number, limit: number, where: Object,attributes: Array<string>,model:any}  = options
        if (options.multi) {
            let {rows,count} = await model.findAndCountAll({
                attributes,
                where: {
                    [Op.and]: {
                        ...where
                    }
                },
                offset: startPosition,
                limit
            })
            return {total: count, data: rows}
        } else {
            let res = await model.findAndCountAll({
                attributes,
                where: {
                    ...where
                },
                offset: startPosition,
                limit
            })
            return {total: res.count, data:res.rows}
        }

    }
  // 获取系统报警信息
    async getErrorList(page: number, pageSize: number, queryDate: string, queryType: string, keywords: string, gateway_ip: string = '') {
    let startPosition: number = (page - 1) * pageSize
    let whereCondition: any = {}
    
    // 构建查询条件
    if (queryDate) whereCondition.date = queryDate
    if (queryType) whereCondition.state = queryType
    if (keywords) whereCondition.info = {[Op.like]: `%${keywords}%`}
    if (gateway_ip) whereCondition.gateway_ip = gateway_ip
    
    try {
        let {rows, count} = await MsgModel.findAndCountAll({
            offset: startPosition,
            limit: pageSize,
            where: whereCondition,
            order: [['createdAt', 'DESC']]
        })
        return {data: rows, total: count}
    } catch (err) {
        console.log(err)
        return {data: [], total: 0}
    }
   }
    // 添加报警信息
    async addErrorInfo(module_id: number, info: string, level: number, date: string, state: number, error_value: number, type_id: number, gateway_ip: string,gateway_name: string) {
       let res = await MsgModel.create({
        module_id,
        info,
        date,
        state,
        level,
        error_value,
        type_id,
        gateway_name,
        gateway_ip // 新增网关IP字段
    })
    return res
    }

    async removeErrorRecord(rid:number) {
        let res: number = await MsgModel.destroy({
            where: {
                rid
            }
        })
        return res
    }
    async updateErrorState(rid:number,state:number) {
        let res = await MsgModel.update({state},{
            where: {
                rid
            }
        })
        return res[0]
    }

    async getErrorNum(p1: string, p2: string, p3: string, gateway_ip: string = '') {
    let baseCondition: any = {}
    if (gateway_ip) baseCondition.gateway_ip = gateway_ip
    
    let num1 = await MsgModel.count({
        where: {
            ...baseCondition,
            date: p1
        }
    })
    
    let num2 = await MsgModel.count({
        where: {
            ...baseCondition,
            createdAt: {
                [Op.between]: [p2, dayjs().add(1, 'day').format('YYYY-MM-DD')]
            }
        }
    })
    
    let num3 = await MsgModel.count({
        where: {
            ...baseCondition,
            createdAt: {
                [Op.between]: [p3, dayjs().add(1, 'day').format('YYYY-MM-DD')]
            }
        }
    })
    
    return [num1, num2, num3]
 }

  // 新增：按网关IP、模块ID、类型ID和日期分组统计报警次数
    async getErrorStatsByModule(gateway_ip: string, type_id?: number, module_id?: number) {
        
        try {
            let whereCondition: any = {
                gateway_ip,
            }
            if (type_id !== undefined) whereCondition.type_id = Number(type_id)
            if (module_id !== undefined) whereCondition.module_id = Number(module_id)
            // 按日期分组统计
            let result = await MsgModel.findAll({
                attributes: [
                    'date',
                    'type_id',
                    [Sequelize.fn('COUNT', '*'), 'count']
                ],
                where: whereCondition,
                group: ['date'],
                order: [['date', 'DESC']],
                raw: true
            })
            
            return result
        } catch (err) {
            console.log('getErrorStatsByModule error:', err)
            return []
        }
    }

    // 通过类型来判断这个报警统计
    async getErrorStatsByType(type: number,gateway_ip?: string) {

         if (gateway_ip) {
            try {
                const result = await MsgModel.findAll({
                    attributes: [
                        'type_id',
                         "date",
                        [Sequelize.fn('COUNT', Sequelize.col('type_id')), 'count']
                    ],
                    where: { type_id: type, gateway_ip },        // 添加网关IP条件
                    group: ['type_id','date'],
                    order: [['count', 'DESC']],
                    raw: true
                })
                return result
            } catch (error) {
                console.log(error)
                return error
            }
            } else {
            try {
                const result = await MsgModel.findAll({
                    attributes: [
                        'type_id',
                        "date",
                        [Sequelize.fn('COUNT', Sequelize.col('type_id')), 'count']
                    ],
                    where: { type_id: type },

                    group: ['type_id','date'],
                    order: [['count', 'DESC']],
                    raw: true
                })
                return result
            } catch (error) {
                console.log(error)
                return error
            }
        }
    }

    // 通过网关ip地址然后判断报警
    async getErrorStatsByGatewayIp() {
        try {
            const result = await MsgModel.findAll({
                attributes: [
                    'gateway_ip',
                    'gateway_name',
                    [Sequelize.fn('COUNT', Sequelize.col('gateway_name')), 'count']
                ],
                group: ['gateway_name'],
                order: [['count', 'DESC']]
            })
            return result;
        } catch (error) {
            console.error('Error fetching error stats by gateway IP:', error);
            throw error;
        }
    }
}

export default new ErrorService();